<template>
    <view class="content">
        <van-popup position="bottom" @click-overlay="closePopup" :show="show" round z-index=104
            custom-style="width: 100%;background:#ffffff;overflow: hidden; height:60%">
            <view class="popup-content">
                <view class="popup-main">
                    <view style="display: flex; justify-content: space-between; padding-bottom: 10rpx;">
                        <view class="popupTitle"> {{title}}</view>
                        <van-icon name="cross" size="15" @click="closePopup" />
                    </view>
                    <scroll-view :refresher-enabled="false" class="scroll-content" scroll-y :lower-threshold="120" show-scrollbar="false">
                        <view class="houseList" v-if="houseList.length > 0">
                            <!-- <radio-group @change="radioChange"> -->
                            <van-radio-group :value="addressId" @change="radioChange">
                                <view class="listItem" v-for="(item, index) in houseList" :key="index" :id="item.id">
                                    <view class="listItemLeft">
                                        <van-radio color="#FF6203" :name="item.id" ></van-radio>
                                        <view style="margin-left: 10px;">
                                            <view style="display: flex; align-items: center;">
                                                <view class="default" v-if="item.isDefault">默认</view>
                                                <view class="name">{{ item.realName }}</view>
                                                <view class="tel">{{ item.phone }}</view>
                                            </view>
                                            <view style="display: flex; align-items: center; margin-top: 12px;">
                                                <view class="house"><text> {{ item.detail }}</text></view>
                                            </view>
                                        </view>

                                    </view>
                                    <view class="iconDiv">
                                        <view class="icon" @click="toEditHouse(item)"><img class="icon"
                                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/edit.png"
                                                alt="" />
                                        </view>
                                    </view>
                                </view>
                            </van-radio-group>
                        </view>
                        <view class="houseList" v-if="houseList.length === 0">
                            <!-- <radio-group @change="radioChange"> -->
                                <view class="listItem">
                                    <view class="listItemLeft">
                                        <view>
                                            <view style="display: flex; align-items: center;">
                                                <view class="name">{{ userName }}</view>
                                                <view class="tel">{{ userTel }}</view>
                                            </view>
                                            <view style="display: flex; align-items: center; margin-top: 12px;">
                                                <view class="house"><text> 绑定房屋后显示房屋信息</text></view>
                                                <view class="button"  @tap="addAddress" >去绑定</view>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            <!-- </radio-group> -->
                        </view>
                        <!-- <van-button type="primary"  @tap="addAddress">新增地址</van-button> -->
                    </scroll-view>
                    <van-toast id="van-toast" />
                </view>
                <view class="btn-area">
                    <van-button type="primary" @tap="addAddress" v-if="pageBiaoshi!='orderDetails'">新增地址</van-button>
                    <van-button type="primary" @tap="submitEdit()" v-else>确认</van-button>
                </view>
            </view>
        </van-popup>
    </view>
</template>

<script>
import Toast from '@/wxcomponents/vant/toast/toast'
import { modifyOrderAddressApi } from '@/api/order'

export default {
    props: {
        show: {
            type: Boolean,
            default: () => false
        },
        house:{
            type: Number,
            default: () => 1  //0是有房子  1是没房子
        },
        orderId:{
            type: String,
            default: () => ''
        },
        pageBiaoshi:{
            type: String,
            default: () => ''
        },
        ebUserAddressList:{
            type: Array,
            default: () => []
        },
        wxUserBaseInfo:{
            type: Object,
            default: () => ({})
        },
        addressInfo:{
            type: Object,
            default: () => ({})
        },
        newAddressId:{
            type: String,
            default: () => ''
        },
        pageType:{
            type: String,
            default: () => ''
        }
    },
    data () {
        return {
            curS:0,
            curSName:'',
            date: '',
            showMark: true, // 标记
            title: '我的地址',
            option: {},
            url: '',
            stepperValue:1,
            houseList:[
                // {
                // name:'王涛员',
                // tel:'1523623254',
                // house:'金鑫·滨湖一号3号楼1单元201',
                // isDefault:true
                // },
                // {
                //     name:'王涛员',
                //     tel:'1523623254',
                //     house:'金鑫·滨湖一号3号楼1单元201',
                //     isDefault:false
                // },
            ],
            userName:'王涛员',
            userTel:'1523623254',
            checkAll: false, // 标记是否全选
            checked: [], // 全选
            selectedRowKeys: [], // 已选择的数据的id
            selectedRows: [], // 已选择的数据
            inactiveIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/notChecked1126.png',
            activeIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/goodsChecked1126.png',
            disabledIcon:'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/disabledIcon.png',
            
            // popupHeight:'300',
            radio:1,
            addressId:'',// 选中的地址id
            windowHeight: 0, // 添加窗口高度存储
        }
    },

// 修改计算属性
computed: {
    popupHeight() {
        if (this.houseList.length === 0) return 300;
        return Math.min(this.windowHeight * 0.7, this.windowHeight - 200); // 改为纯数值计算
    },
    scrollHeight() {
        return this.popupHeight - 120; // 计算滚动区域高度
    }
},


  watch:{
      wxUserBaseInfo: {
          immediate: true, // 这句重要
          handler(v) {
              console.log(v, 'v')
              this.userName = v?.realName || v?.nickName || ''
              this.userTel = v?.phone || ''
          },
          deep: true
      },
      ebUserAddressList: {
          immediate: true, // 这句重要
          handler(v) {
              console.log(v, 'ebUserAddressList -- myHouse')
              this.houseList = this.ebUserAddressList
              if (this.houseList.length > 0) {
                  this.setIsChecked()
              }
          }
      },
      orderId: {
          immediate: true, // 这句重要
          handler(v) {
              console.log(v, 'orderId -- myHouse')
            //   this.orderId = v
          }
      },
      addressInfo: {
          immediate: true, // 这句重要
          handler(v) {
              console.log(v, 'addressInfo -- myHouse')
              this.addressId = v?.id || ''
          }
      }
  },
    onLoad () { },
    onReady () {
        console.log(this.ebUserAddressList,this.houseList,'onready')
        const systemInfo = uni.getSystemInfoSync();
        this.windowHeight = systemInfo.windowHeight;
    },

    methods: {
        // 插入 isChecked
        setIsChecked(){
            if (this.houseList.length > 0) {
                // 1. 优先处理newAddressId（新增地址后需要选中新地址）
                if (this.newAddressId){
                    this.houseList.forEach(item => {
                        const isChecked = item.id === this.newAddressId;
                        this.$set(item, 'isChecked', (item.id ==this.newAddressId))
                        if (isChecked) this.addressId = item.id; // 同步更新选中ID
                    })
                }else{
                    // 2. 无newAddressId时，查找默认地址（isDefault为1或true）
                    const defaultItem = this.houseList.find(item =>
                        item.isDefault === 1 || item.isDefault === true
                    );
                    if (defaultItem) {
                        // 3. 存在默认地址：仅默认地址设为选中
                        this.houseList.forEach(item => {
                            const isChecked = item.id === defaultItem.id;
                            this.$set(item, 'isChecked', isChecked);
                            if (isChecked) this.addressId = item.id; // 同步更新选中ID
                        });
                    } else {
                        // 4. 无默认地址：选中第一个地址
                        this.houseList.forEach((item, index) => {
                            const isChecked = index === 0;
                            this.$set(item, 'isChecked', isChecked);
                            if (isChecked) this.addressId = item.id; // 同步更新选中ID
                        });
                    }
                }
                
            }
        },
        // 单选框
        radioChange(e){
            console.log('radio发生change事件，携带value值为：', e.detail)
            this.addressId = e.detail

            // this.houseList.forEach((item,index)=>{
            //     console.log(index,'index',typeof(index),typeof(e.detail.value), Number(index)=== Number(e.detail.value))
            //     if(Number(index)=== Number(e.detail)){
            //         item.isChecked=true
            //     }else{
            //         item.isChecked=false
            //     }
            // })
            if(this.pageBiaoshi == 'preBookedService' || this.pageBiaoshi == 'settlement'){
                this.$emit('closeHouse',this.addressId)
                return false
            }
            // 已经下单的商品  点击切换地址后  需要调用接口 修改地址
            if(this.pageBiaoshi !== 'orderDetails'){
                this.submitEdit(this.addressId)
                return false
            }
            // this.submitEdit(this.addressId)
        },
       
        // 关闭弹窗
        closePopup () {
            console.log('关闭 关闭关闭---------')
            this.$emit('closeHouse')
        },
        // 点击radio后面的文字
        onChange(val,item){
            console.log(val,item,'----onChange')
            item.isChecked=!item.isChecked
            if(item.isChecked){
              this.addressId=item.id
            }
            debugger
            this.submitEdit()
        },

        // 新增地址
        addAddress(){
            const params = {
                handle:'add',
                pageBiaoshi:this.pageBiaoshi
            }
            uni.navigateTo({
                url:
                    '/pages/address/addAddress?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
            // if(this.pageBiaoshi==='preBookedService'){
            //     uni.navigateTo({
            //         url:
            //             '/pages/address/addAddress?params=' +
            //             encodeURIComponent(JSON.stringify(params))
            //     })
            //     return
            // }else{
            //     uni.navigateTo({
            //         url:
            //             '/pages/address/editMyHouse?params=' +
            //             encodeURIComponent(JSON.stringify(params))
            //     })
            // }
        },
        // 确定修改地址  订单部分  修改地址 是切换即修改 
        submitEdit(){
            debugger
            if(this.houseList.length>0){
                console.log(this.addressId,'this.addressId',this.orderId,'orderId')
                modifyOrderAddressApi(this.orderId,this.addressId).then(res=>{
                    console.log(res,'res')
                    if(res.code===200){
                        Toast(res.msg)
                    }else{
                        Toast(res.msg)
                    }
                })
            }
            this.closePopup()
            this.$emit('submitEditAddress',this.addressId)
        },

        // 重置
        onClickReplay(){},

        // 确定    分类+价格区间
        onClickCart(){
            // this.$emit('onClickCart')
            if(this.curWeight< 0){
                Toast('请选择重量')
            }
            Toast('加入购物车成功')
            // Toast('res.msg')
        },

        // 跳转绑定房子页面
        toEditHouse(item) {
            console.log('跳转')
            const params={}
            params.item=item
            params.pageBiaoshi = this.pageBiaoshi
            // if(params.pageBiaoshi==='preBookedService'){
            //     uni.navigateTo({
            //         url:
            //             '/pages/address/addAddress?params=' +
            //             encodeURIComponent(JSON.stringify(params))
            //     })
            //     return
            // }
            uni.navigateTo({
                url:
                    '/pages/address/editMyHouse?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
        },

  },

}
</script>
<style lang="scss" scoped>

::v-deep .van-button__text {
    // display: inline-block;
    display: flex !important;
    flex-direction: column !important;
}
// 最外层
.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    overflow-y: auto;
    z-index: -2;
    scrollbar-width: none;
    /* 针对Firefox */
}
// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}
// 提示框
.popup-content {
    padding:24px;
    font-size: 12px;
    background: #ffffff;
    border-radius: 16px;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;


    .popup-main {
        height: calc(100% - 30px);
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
    }


    .popupTitle {
        font-size: 20px;
        text-align: left;
        color: #111111;
        line-height: 20px;
    }


    .JOpopup-content {
        padding-top: 23px;

    }

    .houseList { // 异常数据列表
        // padding: 4px 24px 8px;
    }
}


.listItem {
    height: 108rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 58rpx 0rpx;
    border-bottom: 1px solid #f9f9f9;

    .listItemLeft {
        display: flex;
        align-items: center;

        .default{
            font-weight: bolder;
            background: #FFF9F7;
            border-radius: 2px;
            padding: 4px 7px;
            font-size: 12px;
            line-height: 12px;
            text-align: center;
            margin: 0 10px 0 0 ;
            color: #FF6203;
        }
        .name {
            // min-width: 42px;
            font-size: 14px;
            line-height: 14px;
            text-align: left;
            color: #111111;
        }

        .tel {
            line-height: 12px;
            font-size: 12px;
            text-align: left;
            color: #666666;
            margin-left: 11px;
        }

        .house {
            
            font-size: 12px;
            text-align: left;
            color: #666666;
        }


    }

    .iconDiv {
        width: 20%;
        .icon {
            width: 12px;
            height: 12px;
            float: right;
        }
    }
}

.listItem:last-child {
    border-bottom: none;
}

.noBorderLine {
    border-bottom: none;
}

.borderLine {
    border-bottom: 1px solid #ebedf0;
}

.checked-img {
    height: 17px;
    width: 17px;
}

// 去绑定的按钮
.button{
    // width: 100%;
    font-size: 12px;
    color: #ffffff;
    height: 20px;
    line-height:20px;
    border-radius: 10px;
    border-style: initial !important;
    padding: 0 11px !important;
    background: #FF6203 !important;
    margin-left: 13px;
}

::v-deep .van-cell {
    border: 1px solid #888888;
    // background: #FF6203;
}
::v-deep .van-cell--hover .hover-class{
    border: 1px solid #888888;
}


::v-deep .van-button--primary {
    width: 100%;
    height: 86rpx;
    border-radius: 38rpx;
    font-size: 28rpx;
    background: #FF6203 !important;
    border: 1px solid #ff6203 !important;
}

// ::v-deep .van-radio__icon--checked {
//     background-color: var(--radio-checked-icon-color,#FF6203);
//     border-color: var(--radio-checked-icon-color,#FF6203);
//     color: #fff;
// }
::v-deep .listItemLeft .van-radio__icon--checked {
    background-color: #ff6203 !important;
    border-color: #ff6203 !important;
    color: #fff;
}
.l20 {
    margin-left: 20px;
}

.r13 {
    margin-right: 13px;
}

.r8 {
    margin-right: 8px;
}

</style>

